// Package controllerIndex
// @Description:后台控制器
package controllerIndex

import (
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"go-member/controller/common"
	"go-member/db"
	"go-member/model"
	"go-member/tool"
	"go-member/validata"
	"strconv"
)

type Auth struct {
	Id       int
	Username string
}

// UserList
// @Description:用户列表数据
// @return gin.HandlerFunc
func UserList() gin.HandlerFunc {
	return func(c *gin.Context) {
		mysql := db.InitMysql()
		defer mysql.Close()
		name := c.Query("name")
		phone := c.Query("phone")
		page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
		if name != "" {
			mysql = mysql.Where("name LIKE ?", "%"+name+"%")
		}
		if phone != "" {
			if len(phone) == 4 {
				mysql = mysql.Where("RIGHT(phone,4) = ?", phone)
			} else {
				mysql = mysql.Where("phone = ?", phone)
			}
		}
		var count uint
		user := new([]model.User)
		mysql.Model(&user).Debug().Count(&count)
		pageSize, _ := strconv.Atoi(tool.GetEnvDefault("web-user-page-size", "10"))
		mysql.Limit(pageSize).Offset((page - 1) * pageSize).Order("id DESC").Debug().Find(user)
		dataStruct := model.UserStruct{}
		dataStruct.List = user
		dataStruct.Total = count
		dataStruct.CurrentPage = uint(page)
		common.Success(c, "success", dataStruct)
	}
}

// AddUser
// @Description:添加用户
// @return gin.HandlerFunc
func AddUser() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 表单验证
		a := validata.Check(ctx, validata.AddUserRule())
		if a != nil {
			common.ErrorBadRequest(ctx, a)
			return
		}
		//整理数据
		name := ctx.PostForm("name")
		phone := ctx.PostForm("phone")
		categoryId := ctx.PostForm("category_id")
		note := ctx.PostForm("note")
		categoryInfo, _ := model.GetCageGoryById(categoryId)
		mysql := db.InitMysql()
		defer mysql.Close()
		user := model.AddUser{
			Name:       name,
			Phone:      phone,
			Money:      categoryInfo.Money,
			Number:     categoryInfo.Number,
			Created_at: tool.Now(),
			Updated_at: tool.Now(),
		}

		// 添加逻辑处理
		tx := mysql.Begin()
		userErr := tx.Table("user").Debug().Create(&user).Error
		investLog := model.InvestLog{
			User_id:     user.Id,
			Name:        user.Name,
			Phone:       user.Phone,
			C_id:        categoryInfo.Id,
			Money:       categoryInfo.Money,
			Number:      categoryInfo.Number,
			Title:       categoryInfo.Title,
			Note:        note,
			Invest_type: model.CREATE_USER,
			Created_at:  tool.Now(),
			Updated_at:  tool.Now(),
		}

		investErr := tx.Table("invest_log").Debug().Create(&investLog).Error
		if userErr != nil || investErr != nil {
			tx.Callback()
			common.Error(ctx, "添加失败")
			return
		}

		tx.Commit()
		common.Success(ctx, "添加成功", user)
	}
}

// UpdateNumber
// @Description: 修改次数
// @return gin.HandlerFunc
func UpdateNumber() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 表单验证
		a := validata.Check(ctx, validata.UpdateNumber())
		if a != nil {
			common.ErrorBadRequest(ctx, a)
			return
		}
		id := ctx.PostForm("id")
		_type := ctx.PostForm("type")
		note := ctx.PostForm("note")
		idInt, _ := strconv.Atoi(id)
		IntType, _ := strconv.Atoi(_type)
		updType := "-"
		if IntType == 1 {
			updType = "+"
		}
		number := uint(1)

		// 逻辑处理
		user, exists := model.GetUserById(id)
		if !exists {
			common.ErrorBadRequest(ctx, "用户不存在")
			return
		}
		numberLog := model.NumberLog{
			User_id:    uint(idInt),
			Name:       user.Name,
			Phone:      user.Phone,
			Upd_type:   uint(IntType),
			Number:     number,
			Note:       note,
			Created_at: tool.Now(),
			Updated_at: tool.Now(),
		}
		mysql := db.InitMysql()
		defer mysql.Close()
		tx := mysql.Begin()
		// 修改次数
		errUser := tx.Table("user").Debug().Where("id=?", id).Updates(
			map[string]interface{}{
				"number":     gorm.Expr("number"+updType+"?", number),
				"updated_at": tool.Now(),
			},
		).Error
		// 日志记录
		errNumber := tx.Table("number_log").Debug().Create(&numberLog).Error
		if errUser != nil || errNumber != nil {
			common.Error(ctx, "操作失败")
			tx.Rollback()
			return
		}
		tx.Commit()
		common.Success(ctx, "操作成功", "")
	}
}

// Invest
// @Description: 充值
// @return gin.HandlerFunc
func Invest() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		checkMsg := validata.Check(ctx, validata.Invest())
		if checkMsg != nil {
			common.ErrorBadRequest(ctx, checkMsg)
			return
		}

		id := ctx.PostForm("id")
		categoryId := ctx.PostForm("category_id")
		note := ctx.PostForm("note")

		user, exists := model.GetUserById(id)
		if !exists {
			common.ErrorBadRequest(ctx, "用户不存在")
			return
		}
		category, exists := model.GetCageGoryById(categoryId)
		if !exists {
			common.ErrorBadRequest(ctx, "分类不存在")
			return
		}

		investLog := model.InvestLog{
			User_id:     user.Id,
			Name:        user.Name,
			Phone:       user.Phone,
			C_id:        category.Id,
			Money:       category.Money,
			Number:      category.Number,
			Title:       category.Title,
			Note:        note,
			Invest_type: model.INVEST,
			Created_at:  tool.Now(),
			Updated_at:  tool.Now(),
		}

		mysql := db.InitMysql()
		defer mysql.Close()
		tx := mysql.Begin()
		// 充值
		errUser := tx.Table("user").Where("id=?", id).Updates(
			map[string]interface{}{
				"number":     gorm.Expr("number+?", category.Number),
				"money":      gorm.Expr("money+?", category.Money),
				"updated_at": tool.Now(),
			},
		).Error
		// 日志记录
		errInvest := tx.Table("invest_log").Debug().Create(&investLog).Error
		if errUser != nil || errInvest != nil {
			fmt.Println("invest-user-err:", errUser)
			fmt.Println("Invest-log-err:", errInvest)
			common.Error(ctx, "操作失败")
			tx.Rollback()
			return
		}

		tx.Commit()
		common.Success(ctx, "操作成功", "")
	}
}

// DelUser
// @Description: 删除用户(软删除)
// @return gin.HandlerFunc
func DelUser() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 表单验证
		a := validata.Check(ctx, map[string]string{
			"id.required":   "缺少关键数据",
			"id.uint":       "错误的数据类型",
			"id.existsUser": "未找到该用户",
		})
		if a != nil {
			common.ErrorBadRequest(ctx, a)
			return
		}
		id := ctx.PostForm("id")
		mysql := db.InitMysql()
		defer mysql.Close()
		tx := mysql.Begin()
		if err := tx.Table("user").Debug().Where("id=?", id).Update("deleted_at", tool.Now()).Error; err != nil {
			tx.Callback()
			common.Error(ctx, "删除失败")
			return
		}
		tx.Commit()
		common.Success(ctx, "删除成功", "")
	}
}

// RecoverUser
// @Description: 恢复用户
// @return gin.HandlerFunc
func RecoverUser() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 表单验证
		a := validata.Check(ctx, map[string]string{
			"id.required":      "缺少关键数据",
			"id.uint":          "错误的数据类型",
			"id.existsDelUser": "未找到该数据",
		})
		if a != nil {
			common.ErrorBadRequest(ctx, a)
			return
		}
		id := ctx.PostForm("id")
		mysql := db.InitMysql()
		defer mysql.Close()
		tx := mysql.Begin()
		if err := tx.Table("user").Debug().Where("id=?", id).Updates(
			map[string]interface{}{
				"deleted_at": gorm.Expr("NULL"),
				"updated_at": tool.Now(),
			},
		).Error; err != nil {
			tx.Callback()
			common.Error(ctx, "恢复失败")
			return
		}
		tx.Commit()
		common.Success(ctx, "恢复成功", "")
	}
}

// EditUser
// @Description: 编辑用户
// @return gin.HandlerFunc
func EditUser() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		check := validata.Check(ctx, validata.EditUserRule())
		id := ctx.PostForm("id")
		name := ctx.PostForm("name")
		phone := ctx.PostForm("phone")
		if check != nil {
			common.ErrorBadRequest(ctx, check)
			return
		}
		_, exists := model.GetUserById(id)
		if !exists {
			common.ErrorBadRequest(ctx, "用户不存在")
			return
		}
		mysql := db.InitMysql()
		existsUser := model.User{}
		err := mysql.Debug().Where("id!= ?", id).Where("name=?", name).First(&existsUser).Error
		if err != gorm.ErrRecordNotFound {
			common.ErrorBadRequest(ctx, "姓名已存在")
			return
		}
		defer mysql.Close()
		tx := mysql.Begin()
		if err := tx.Table("user").Debug().Where("id=?", id).Updates(
			map[string]interface{}{
				"name":       name,
				"phone":      phone,
				"updated_at": tool.Now(),
			},
		).Error; err != nil {
			tx.Callback()
			common.Error(ctx, "编辑失败")
			return
		}
		tx.Commit()
		common.Success(ctx, "编辑成功", "")
	}
}
